<template lang='pug'>
  .page
    .search-form.mb-10.pl-10.pr-10
      Row(type="flex" justify="start")
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 团队名称：
          Input(v-model="searchData.Name" placeholder="请输入" clearable)
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          Button.ml-15(v-if="hasFind" type="info" @click="searchBtn") 查询
    .pl-20.pr-20.bg-white
      Table.hasTitle-table.beautiful-table(width="100%" :loading="loading" stripe :columns="thead" :data="listData")
        div(slot="header")
          .pull-left.table-title-lefttxt
            span.leftText
              | 合计:
              span.text-info.pl-5.pr-5.font-weight {{totalRows}}
              | 条
          .pull-right.table-title-btns
            Button.mr-15(v-if="hasAdd" type="info" @click="creatBtn") 新建
        template(slot-scope="{ row, index }" slot="enabled")
          span {{row.enabled ? '已启用' : '已禁用'}}
        template(slot-scope="{ row, index }" slot="action")
          Button.mr-15(v-if="hasEnabled && !row.enabled" type="info" size="small" @click="enabledBtn(row.id, true, '启用')") 启用
          Button.mr-15(v-if="hasDisEnabled && row.enabled" type="error" size="small" @click="enabledBtn(row.id, false, '禁用')" ghost) 禁用
          Button(v-if="hasDisEnabled" type="info" size="small" @click="editBtn(row.id)" ghost) 编辑
        .clearfix.pl-20.pr-20(slot="footer")
          Page(:total="totalRows" :current="searchData.PageIndex" :page-size="searchData.PageSize" prev-text="上一页" next-text="下一页" @on-change="pageChangeFn" show-total @on-page-size-change="onpageSizeChange" show-sizer :page-size-opts="[10, 20, 30, 50, 100]")
    Modal(v-model="addModal" :title="modalText" width="800")
      Form(ref="formValidate" :model="teamInfo" :rules="ruleValidate" :label-width="100")
        FormItem(label="团队名称：" prop="name")
          Input.input-has-border(v-model="teamInfo.name" placeholder="请输入团队名称")
        FormItem(label="团队成员：" prop="memberName")
          Input.input-has-border(v-model="teamInfo.memberName" style="display:none")
          .choose-saler
            Tooltip(placement="bottom" max-width="200" :disabled="!tipIsShow" theme="light")
              //- Input.input-has-border.input(v-model="teamInfo.memberName" type="text" disabled clearable @on-clear="salersClear")
              .has-border
                span {{teamInfo.memberName}}
                Icon(v-if="tipIsShow" type="ios-close-circle" size="18" @click="salersClear")
              div(slot="content")
                .font-14 {{teamInfo.memberName}}
            .button(@click="chooseSaler") 选择
        FormItem(label="是否启用：" )
          i-switch(v-model="teamInfo.enabled" size="large")
            span(slot="open") 启用
            span(slot="close") 禁用
      div(slot="footer")
        Button(type="info" @click="saveBtn('formValidate')") 确定
        Button(@click="addModal=false") 取消
    visibvleTreeList(ref="treeModal" :treeData="treeData" @on-change="getSelectId")
</template>

<script>
import SaleTeamApi from './service.js'
import visibvleTreeList from '../../HRDC-common/visibleTreeList.vue'

export default {
  name:'',
  props:{},
  data () {
    return {
      searchData: {
        Name: '',
        PageIndex: 1,
        PageSize: 10
      },
      modalText: '新建团队',
      addModal: false,
      teamInfo: {
        name: '',
        memberIds: '',
        memberName: '',
        enabled: true
      },
      ruleValidate: {
        name: [
          { required: true, message: '团队名称不能为空', trigger: 'blur' }
        ],
        memberName: [
          { required: true, message: '请选择团队成员', trigger: 'change' }
        ]
      },
      treeData: [],
      thead: [
        {
          title: '团队名称',
          width: 150,
          align: 'center',
          key: 'name'
        },
        {
          title: '团队成员',
          minWidth: 350,
          align: 'center',
          key: 'memberName'
        },
        {
          title: '状态',
          width: 150,
          align: 'center',
          key: 'enabled',
          slot: 'enabled',
        },
        {
          title: '操作',
          width: 250,
          align: 'center',
          slot: 'action',
        },
      ],
      loading: false,
      listData: [],
      totalRows: 0
    };
  },

  components: {
    visibvleTreeList
  },

  computed: {
    tipIsShow () {
      if (this.teamInfo.memberIds) {
        return true
      } else {
        return false
      }
    },
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 查询
    hasFind () {
      return this.actionArr.indexOf('Find') > -1
    },
    // 新建
    hasAdd () {
      return this.actionArr.indexOf('Add') > -1
    },
    // 启用
    hasEnabled () {
      return this.actionArr.indexOf('Enabled') > -1
    },
    // 禁用
    hasDisEnabled () {
      return this.actionArr.indexOf('DisEnabled') > -1
    },
  },

  beforeMount() {},

  mounted() {
    this.getList()
    this.getVisibleTreeList()
  },

  methods: {
    creatBtn () {
      this.modalText = '新建团队'
      this.addModal = true
      this.teamInfo = {
        name: '',
        memberIds: '',
        memberName: '',
        enabled: true
      }
      this.getVisibleTreeList()
      this.$refs['formValidate'].resetFields()
    },
    getList () {
      this.loading = true
      SaleTeamApi.GetList(this.searchData).then(res => {
        this.loading = false
        if (res.data.success) {
          this.listData = res.data.data
          this.totalRows = res.data.totalRows
        } else {
          this.$Message.error(res.data.message)
        }
      })
    },
    searchBtn () {
      this.searchData.PageIndex = 1
      this.getList()
    },
    enabledBtn (id, type, text) {
      this.$Modal.confirm({
        title: '确定' + text + '？',
        onOk: () => {
          this.enabledFn(id, type)
        },
        onCancel: () => {
        }
      });
    },
    enabledFn (id, type) {
      SaleTeamApi.EnabledList({
        ids: id,
        enabled: type
      }).then(res => {
        if (res.data.success) {
          this.$Message.success('操作成功！')
          this.getList()
        } else {
          this.$Message.error(res.data.message)
        }
      })
    },
    chooseSaler () {
      this.$refs.treeModal.show()
    },
    getSelectId (val) {
      let idArr = []
      let nameArr = []
      val.forEach(item => {
        if (item.type === "4") {
          idArr.push(item.id)
          nameArr.push(item.title)
        }
      })
      this.teamInfo.memberIds = idArr.join(',')
      this.teamInfo.memberName = nameArr.join(',')
    },
    salersClear () {
      this.teamInfo.memberIds = ''
      this.teamInfo.memberName = ''
      this.getVisibleTreeList()
    },
    saveBtn (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          SaleTeamApi.Save(this.teamInfo).then(res => {
            if (res.data.success) {
              this.$Message.success(res.data.message)
              this.addModal = false
              this.getList()
              this.getVisibleTreeList()
              this.$refs[name].resetFields()
            } else {
              this.$Message.error(res.data.message)
            }
          })
        } else {
        }
      })
    },
    // 获取当前角色可见的销售人员
    getVisibleTreeList () {
      SaleTeamApi.GetVisibleTreeList().then(res => {
        this.treeData = res.data.data
      })
    },
    pageChangeFn (val) {
      this.searchData.PageIndex = val
      this.getList()
    },
    onpageSizeChange (val) {
      this.searchData.PageSize = val
      this.getList()
    },
    dateChange (val) {
      this.searchData.Date = val
    },
    editBtn (id) {
      this.modalText = '编辑团队'
      this.addModal = true
      SaleTeamApi.GetModel({
        id: id
      }).then(res => {
        if (res.data.success) {
          this.teamInfo = res.data.data
          let memberIds = this.teamInfo.memberIds.split(',')
          console.log(memberIds)
          SaleTeamApi.GetVisibleTreeList().then(res => {
            this.treeData = res.data.data
            memberIds.forEach(item => {
              this.recursive(item, this.treeData)
            })
          })
        } else {
          this.$Message.error(res.data.message)
        }
      })
    },
    // 回显
    recursive (id, parentArr) {
      parentArr.forEach((_tree) => {
        if (id.toUpperCase() === _tree.id) {
          _tree.checked = true
        } else {
          if (_tree.children.length > 0) {
            this.recursive(id, _tree.children)
          }
        }
      })
    }
  },

  watch: {}

}

</script>
<style lang="less" scoped>
  .has-border{
    height: 36px;
    border: 1px solid #dcdee2;
    border-radius: 8px;
    padding: 0 75px 0 15px;
    position: relative;
    .ivu-icon{
      position: absolute;
      top: 8px;
      right: 55px;
      cursor: pointer;
    }
  }
</style>